import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'entity/flow_tts_entity.dart';
import 'entity/init_entity.dart';
import 'plugin_asr_platform_interface.dart';

/// An implementation of [PluginAsrPlatform] that uses method channels.
class MethodChannelPluginAsr extends PluginAsrPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('plugin_asr');

  toJsonString(Map<String, dynamic> map) {
    return json.encode(map);
  }

  @override
  Future<int?> init(InitEntity initEntity) async {
    String str = toJsonString(initEntity.toJson());
    final ret = await methodChannel.invokeMethod<int>('init', str);
    return ret;
  }

  @override
  Future<String?> startAsrListener(String language) async {
    final ret = await methodChannel.invokeMethod<String>('startAsrListener', language);
    return ret;
  }

  @override
  Future<int?> stopAsrListener() async {
    final ret = await methodChannel.invokeMethod<int>('stopAsrListener');
    return ret;
  }

  @override
  Future<int?> startOnlineTTS(String text) async {
    final ret = await methodChannel.invokeMethod<int>('startOnlineTTS', text);
    return ret;
  }

  @override
  Future<int?> stopOnlineTTS() async {
    final ret = await methodChannel.invokeMethod<int>('stopOnlineTTS');
    return ret;
  }

  @override
  Future<int?> startPersonTTS(String text) async {
    final ret = await methodChannel.invokeMethod<int>('startPersonTTS', text);
    return ret;
  }

  @override
  Future<int?> startFlowPersonTTS(FlowTtsEntity flowTtsEntity) async {
    String str = toJsonString(flowTtsEntity.toJson());
    final ret = await methodChannel.invokeMethod<int>('startFlowPersonTTS', str);
    return ret;
  }

  @override
  Future<int?> stopPersonTTS() async {
    final ret = await methodChannel.invokeMethod<int>('stopPersonTTS');
    return ret;
  }

  @override
  Future<void> setupNativeMessageListener(Function onEvent) async {
    methodChannel.setMethodCallHandler((call) async {
      onEvent(call);
    });
  }

  @override
  Future<String?> getPlatformVersion() async {
    final version = await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }
}
